package ch.zbw.pra.sysventory.network.server;

import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import ch.zbw.pra.sysventory.domain.dbconnector.IDBConnector;
import ch.zbw.pra.sysventory.domain.dbhandling.InsertScanversionIntoDB;
import ch.zbw.pra.sysventory.domain.model.Scanversion;
import ch.zbw.pra.sysventory.domain.util.MyLogger;

public class ConnectionHandler implements Runnable {

	private static final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(ConnectionHandler.class);

	private Socket socket;
	private ObjectInputStream ois;
	private ObjectOutputStream oos;
	private Thread t;
	private Scanversion scanversion;
	private boolean isScanning;
	private IDBConnector dbconnector;
	private boolean scanFinished;

	public ConnectionHandler(Socket socket, IDBConnector dbconnector) {
		this.socket = socket;
		this.dbconnector = dbconnector;
		this.t = new Thread(this);
		this.t.start();
	}

	public void run() {
		try {

			while (!this.socket.isClosed()) {
				if (this.isScanning) {

					this.ois = new ObjectInputStream(new BufferedInputStream(
							this.socket.getInputStream()));
					MyLogger.logDebug(log, "Start reading a Scanversion...");
					this.scanversion = (Scanversion) this.ois.readObject();
					MyLogger.logDebug(log, "... Scanversion read!");
					if (this.scanversion != null) {
						InsertScanversionIntoDB insert = new InsertScanversionIntoDB(
								this.dbconnector);
						insert.insertScanversionIntoDB(this.scanversion);
						MyLogger.logDebug(log, "Scanversion successfully saved in DB: "
								+ this.scanversion.getClass().getName() + " with ComputerName: "
								+ this.scanversion.getComputer().getHostNameComputer());
					}
					this.scanFinished = this.ois.readBoolean();
					this.ois.close();
				}
			}
		} catch (EOFException eof) {
			MyLogger.logError(log, eof.toString());
		} catch (IOException e) {
			MyLogger.logError(log, "Verbindung zu geschlossen!");
		} catch (ClassNotFoundException e) {
			MyLogger.logError(log, e.toString());
		}
	}

	public void setScanning(boolean isScanning) {
		try {
			this.oos = new ObjectOutputStream(this.socket.getOutputStream());
			if (isScanning) {
				this.oos.writeBoolean(true);
			} else if (!isScanning) {
				this.oos.writeBoolean(false);
			}
			this.oos.flush();
		} catch (IOException e) {
			MyLogger.logError(log, e.toString());
		}
		this.isScanning = isScanning;
	}

	public void closeSocket() {
		try {
			this.socket.close();
		} catch (IOException e) {
			MyLogger.logDebug(log, e.toString());
		}
	}

	public boolean isScanFinished() {
		return this.scanFinished;
	}
}
